package logic

import (
	"context"
	"fmt"
	"zhihu/models/mysql"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SpeakAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSpeakAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SpeakAddLogic {
	return &SpeakAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 问题回答
func (l *SpeakAddLogic) SpeakAdd(in *zhihurpc.SpeakAddRequest) (*zhihurpc.SpeakAddResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("id = ?", in.UserId).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("当前用户不存在，无法回答问题")
	}

	var problem mysql.Problem
	mysql.DB.Debug().Where("id = ?", in.ProblemId).Find(&problem)
	if problem.ID == 0 {
		return nil, fmt.Errorf("当前问题不存在，用户无法回答问题")
	}

	speak := mysql.Speak{
		Content:   in.Content,
		UserId:    in.UserId,
		ProblemId: in.ProblemId,
	}
	mysql.DB.Debug().Create(&speak)

	return &zhihurpc.SpeakAddResponse{
		Id: int64(speak.ID),
	}, nil
}
